<template>
  <div>
    <EditorVue
        :content="content"
        :readOnlys="readOnlys"
        @changeData="hChangeData"
        @uploadImg="hUploadImg"
    />
    <el-divider></el-divider>

    <!-- 文档信息编辑 -->
    <div>
      <div class="form">
        <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm" :rules="formRule">

          <el-form-item label="文档标题" prop="title">
            <el-input v-model="ruleForm.title" style="width: 220px;float: left"></el-input>
          </el-form-item>

          <el-form-item label="预览图上传">
          <el-upload
              class="avatar-uploader"
              name="file"
              action="http://124.70.54.24:3001/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          </el-form-item>

          <el-form-item label="文档分类" prop="categoryId">
            <el-select v-model="ruleForm.categoryId" placeholder="请选择文档类别">
              <el-option v-for="option in categorys" :key="option.id" :label="option.categoryName" :value="option.id" style="float: left"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="标签">
<!--            <el-input v-model="newTag" placeholder="请输入标签名称"></el-input>-->
<!--            <el-button @click="addTag">添加标签</el-button>-->
<!--            <el-tag-->
<!--                v-for="(tag, index) in tags"-->
<!--                :key="index"-->
<!--                closable-->
<!--                @close="removeTag(index)"-->
<!--            >-->
<!--              {{ tag }}-->
<!--            </el-tag>-->
            <el-select v-model="selectedTags" multiple placeholder="请选择标签">
              <el-option
                  v-for="tag in tags"
                  :key="tag.id"
                  :label="tag.tagname"
                  :value="tag.tagname"
              >
                <el-tag>{{ tag.tagname }}</el-tag>
              </el-option>
            </el-select>

          </el-form-item>

          <el-form-item style="padding:0px 80px 10px 0px;">
            <el-button type="primary" @click="uploadImg()">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>

        </el-form>
      </div>
    </div>

  </div>
</template>

<script>
import EditorVue from '../components/editorVue.vue'
export default {
  name: "AddNews",
  components: {
    EditorVue,
    // ChooseLocalFile
  },
  //从父组件传过来的数据，为回显的数据
  props: {
    // oldRuleForm:{
    //   type:String, //数据类型有 String、Number、Boolean、Array ...
    //   default:''// 默认值
    // },
    from: {
      type: String,
      default: ''
    },
    dialogFormVisibleAdd: {
      type: Boolean,
      default: true
    }
  },
  data() {
    // this.ruleForm=JSON.parse(this.formData);
    return {
      categorys:[],
      newTag: "", // 新增标签名称
      tags: [], // 存储标签列表
      selectedTags: [], // 存储选中的标签
      form:{
        useravatar:"",
      },
      imageUrl:"",//回显图片地址
      isChecked: false,
      params: new FormData(),
      readOnlys: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      content: '',
      ruleForm: {},
      formRule: {
        title: [
          {required: true, message: '请输入标题名称', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
        categoryId:[
            {required: true, message: '请选择类别', trigger: 'blur'},
        ],
        selectedTags:[
          {validator: (rule, value, callback) => {
              if (this.selectedTags.length>0) {
                callback();
              } else {
                callback(new Error('请选择标签'));
              }
            }, trigger: 'blur'}
        ]
      },
      fileList: []
    };
  },
  methods: {
    //gpt写的
    getTags() {
      // 调用后端接口获取标签列表
      // 假设接口返回的数据格式为 [{ id: 1, name: '标签1' }, { id: 2, name: '标签2' }, ...]
      // 在实际项目中，可以使用axios或fetch来发送请求
      this.$axios.get("http://localhost:8081/tag/findall")
          .then(response => {
            console.log("response")
            console.log(response)
            this.tags = response.data;
          })
          .catch(error => {
            this.$message.error("获取标签失败，请联系管理员")
          });
    },
    publishBlog() {
      // 获取选中的标签
      console.log(this.selectedTags);
      // 执行发布博客的逻辑
      // ...
    },

  //我自己写的
    addTag() {
      if (this.newTag) {
        this.tags.push(this.newTag); // 将新增标签添加到标签列表
        this.newTag = ""; // 清空新增标签名称
      }
    },
    removeTag(index) {
      this.tags.splice(index, 1); // 删除指定位置的标签
      console.log("tags")
      console.log(this.tags);
    },
    //上传图片成功时执行的函数
    handleAvatarSuccess(res){
      console.log('上传请求返回的数据',res)
      if(res.code==200){
        //成功
        this.imageUrl = res.data;
        //赋给修改用户
        this.form.useravatar = res.data;
        console.log("res.data");
        console.log(res.data);
      }
    },
    beforeAvatarUpload(file){
      console.log('上传之前',file);
      //判断大小和类型是否符合条件,最多5m的大小限制，并且只能是png、jpg、jpeg、gif、webp等格式
      //使用正则表达式来判断数据是否符合指定条件
      if(!/(png|jpg|jpeg|gif|webp)$/.test(file.type)){
        this.$message({
          message:"只能上传png、jpg、jpeg、gif、webp格式的图片",
          type:"error"
        })
        return false;
      }
      if(file.size > 1024 *1024 *2){
        this.$message({
          message:"只能上传大小小于2mb的图片",
          type:"error"
        })
        return false;
      }
      return true;//允许上传
    },
    hChangeData(editDataHtml) {
      // 获取最新的html数据
      this.content = editDataHtml
    },
    hUploadImg(file, insertFn) {
      console.log(file)
      // 插入图片，调接口返回图片url,通过插入conteng
      let imgUrl = 'https://img1.baidu.com/it/u=608404415,1639465523&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800'
      insertFn(imgUrl);
      // 设置只读
      // this.readOnlys = true;
    },
    //限定添加新闻图片的图片大小
    // beforeAvatarUpload(file) {
    //   const isLt2M = file.size / 1024 / 1024 < 2;
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!');
    //   }
    //   return isLt2M;
    // },
    // submitForm() {
    //   console.log("content=====================")
    //   console.log(this.content);
    //   this.$refs["ruleForm"].validate((valid) => {
    //     if (valid) {
    //       alert('submit!');
    //       this.$refs.upload.submit();
    //       this.params.append("n_id",this.ruleForm.nId)
    //       this.params.append("n_title",this.ruleForm.nTitle)
    //       this.params.append("n_content",this.content)
    //       this.params.append("n_class",this.ruleForm.nClass)
    //       this.$axios.post("/news/modifyNews/",params).then(
    //           (res) => {
    //             if(res.data.code === 200){
    //               this.$message.success("修改成功!");
    //               // this.$router.push({path:'/allMassage',query:this.ruleForm.nClass});
    //             }
    //             else{
    //               this.$message.error("修改失败")
    //             }
    //
    //           }
    //       )
    //     } else {
    //       console.log('error submit!!');
    //       return false;
    //     }
    //   });
    // },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleChange(event) {
      console.log(event)
      // document.getElementById("img").style.display="block";
    },
    // 文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.params.remove('file');
    },
    uploadFileAndParams(param) {
      this.params.append("pic", param.file)
    },
    handlePreview(file) {
      console.log(file);
    },
    Img(param) {
      this.file = param.file;
    },
    uploadImg() {
      this.$refs.ruleForm.validate((valid) => {
        if(valid){
        // let config = {
        //   headers: {
        //     'Content-Type': 'multipart/form-data'
        //   }
        // };
        // let params = new FormData();
          const jsonString = JSON.stringify(this.selectedTags);
          let params = new FormData();
          params.append('title', this.ruleForm.title)
        // this.params.append('n_author', localStorage.getItem('ms_username'))
          params.append('content', this.content)
          params.append('view',0)
          params.append('tags', jsonString)
          params.append("categoryId", this.ruleForm.categoryId)
          params.append("path", this.imageUrl)
          //重要新闻？
          // this.params.append('n_imporant',this.ruleForm.important)
        this.$axios.post('/tbBlog/add', params).then((res) => {
          if (res.data.code === 200) {
            this.$message.success("上传成功！")
            this.shutdown();
          } else {
            this.$message.error('上传失败！')
          }
        }).finally(() => {
          this.shutdown();
          this.$emit('success', false);
        })}
      });
    },
    shutdown: function () {
      this.$emit('update:shutdown', false)
    },
    getCategorys(){
      this.$axios.get("http://localhost:8081/Category/findall")
          .then(response => {
            console.log("response")
            console.log(response)
            this.categorys = response.data;
          })
          .catch(error => {
            this.$message.error("获取分类失败，请联系管理员")
          });
      // this.categorys=[{name:"前端",id:1},{name:"后端",id:2},{name:"全栈",id:3}]
    },
  },
  mounted() {
    this.getCategorys();
    this.getTags();
  },

};
</script>
<style scoped>
.form {
  width: 400px;
  margin: 0 auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.img {
  padding-bottom: 10px;
}
</style>
